<template>
    <div class="app-container" ref="content">
        <div style="text-align: center;padding: 10px">《{{fireInfoInfo.name}}》-详情信息</div>
        <el-row :gutter="10">
            <el-col :span="12" :offset="6">
              <div style="margin: 10px auto;text-align: center">
                <el-button type="primary" size="mini" @click="show=true" v-if="fireInfoInfo.commander==null&&enterPriseHidden&&fireInfoInfo.fireExecutionStatus!=2" align="center">分配指战员</el-button>
              </div>

                <el-form :model="fireInfoInfo" ref="fireInfoInfo" label-width="100px">
                  <el-form-item label="上报人:" prop="userName">
                    {{ fireInfoInfo.userName }}
                    <el-button type="primary" icon="el-icon-edit" class="filter-item" style="margin-left: 10px" v-if="fireInfoInfo.fireExecutionStatus!=2" @click="launchFireVideo()">发起视频</el-button>
                  </el-form-item>
                    <el-form-item label="上报人电话:" prop="userPhone">
                      {{ fireInfoInfo.userPhone }}
                    </el-form-item>
                    <el-form-item label="所属主体:" prop="enterpriseName">
                        {{ fireInfoInfo.enterpriseName }}
                    </el-form-item>
                    <el-form-item label="预警名称:" prop="fireAlarmName">
                        {{ fireInfoInfo.fireAlarmName }}
                    </el-form-item>
                    <el-form-item label="所属建筑" prop="buildName">
                        {{ fireInfoInfo.buildName }}
                    </el-form-item>
                    <el-form-item label="详情地址:" prop="loaction">
                        {{ fireInfoInfo.loaction  }}
                    </el-form-item>
                    <el-form-item label="确定时间:" prop="fireConfirmTime">
                        {{ fireInfoInfo.fireConfirmTime  |dateFormat}}
                    </el-form-item>
                  <el-form-item label="火情状态:" prop="fireExecutionStatus">
                    {{ fireInfoInfo.fireExecutionStatus|fireStatus }}
                  </el-form-item>
                    <el-form-item label="结束时间:" prop="endTime" v-if="fireInfoInfo.endTime">
                        {{ fireInfoInfo.endTime | dateFormat}}
                    </el-form-item>
                </el-form>
              <div style="margin-top: 10px">
                <baidu-map class="map-view" map-type="BMAP_NORMAL_MAP"  :center="{lng: fireInfoInfo.userLongitude, lat: fireInfoInfo.userLatitude}" :zoom="15" :scroll-wheel-zoom="true">
                  <bm-marker :position="{lng: fireInfoInfo.userLongitude, lat: fireInfoInfo.userLatitude}" :dragging="false" animation="BMAP_ANIMATION_BOUNCE">
                    <bm-label :content="fireInfoInfo.userName" :labelStyle="{color: 'red', fontSize : '12px'}" :offset="{width: 0, height: 30}"/>
                  </bm-marker>
                </baidu-map>
              </div>
                <div style="width: 100%;height: 400px;margin-bottom: 40px" v-if="fireInfoInfo.fireVodie!=null">
                    <video :src="fireInfoInfo.fireVodie"  width="100%" height="400px" controls autoplay></video>
                    <div style="text-align: center">
                        报警视频
                    </div>
                </div>
                <div style="width: 100%;height: 400px;margin-bottom: 40px" v-if="fireInfoInfo.inspectionVideo!=null">
                    <video :src="fireInfoInfo.inspectionVideo"  width="100%" height="400px" controls autoplay></video>
                    <div style="text-align: center">
                        巡检视频
                    </div>
                </div>
            </el-col>
        </el-row>
        <el-dialog title="视频展示区域" :visible.sync="videoDialogVisible" width="50%" style="height: 100vh">
            <div style="position: relative;max-height: 446px">
                <video ref="localVideo" playsinline autoplay width="30%" style="position: absolute;top: 0;left: 0;"></video>
                <video ref="remoteVideo" playsinline autoplay width="100%"  style="height: 340px"></video>
            </div>
            <div style="text-align: center;margin-top: 10px">
                <el-button type="danger" @click="hungUp">挂断</el-button>
            </div>
        </el-dialog>
      <el-dialog title="分配指战员" :visible.sync="show">
        <el-form :model="personForm" ref="personForm" label-width="150px">
            <el-form-item label="指战员" prop="commander">
              <el-select v-model="personForm.commander" placeholder="请选择执行人员" style="width:100%">
                <el-option v-for="(item,index) in userList" :key="index" :value="item.ucId"
                           :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          <div align="center">
            <el-button type="primary" @click="distribution">确定</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
</template>

<script>

import 'aliyun-webrtc-sdk'
import {callPerson, deleteChannel, launchFireVideo} from "@/api/alirtc";
import {getFireInfo, distributionPerson} from "@/api/fireInfo";
import {getInUserList} from "@/api/enterprise";
import {getCommanderList} from "@/api/user";
import {getToken} from "@/utils/auth";


export default {
    name: "fireInfoInfo",
    data(){
        return{
            fireInfoInfo:{

            },
            videoDialogVisible:false,
            channelId:'',
          show:false,
          personForm:{},
          userList:[],

        }
    },
    created() {
        this.getInFireInfoVo(this.$route.params.ucId)
      this.personForm.ucId=this.$route.params.ucId
      this.getCommanderList()
    },
    computed: {
        enterPriseHidden(){
            let roleCode = this.$store.getters.roleCode;
            return roleCode=="XT-ADMIN"
        },
    },
    methods:{
        getInFireInfoVo(val){
            //获取火情信息数据
            let loadingInstance = this.$loading({
                target:this.$refs.content,
                text:'数据加载中'
            });
          getFireInfo({ucId:val}).then(res=>{
                this.fireInfoInfo = res.data
                loadingInstance.close()
                this.$notify.success({
                    title: '成功',
                    message: "获取火情信息成功"
                })

            }).catch(error=>{
                loadingInstance.close()
                this.$notify.error({
                    title: '失败',
                    message: "获取火情信息失败"
                })
            })
        },
        hungUp(){
            this.leaveVideo(true)
        },
        //校验当前设备是否支持
        isSupport(val,debug){
            let option = {}
            if (debug){
                option.isDebug=true
            }
            val.isSupport(option).then((res)=>{
                this.onJoinEvent(val)
                this.onPublisher(val)
                this.onBye(this.aliWebrtc)
                this.onLeave(val)
                this.OnRefresh(val)
            }).catch((error)=>{
                console.log("不支持webrtc",error.message)
            })
        },
        //页面刷新时调用
        OnRefresh(val){
            window.onbeforeunload=function (e) {
                if (!val){
                    console.log("isSupport失败");
                    return ;
                }
                val.leaveChannel();
                val.dispose();
            }
        },
        //本地预览
        startPreview(val){
            this.aliWebrtc.startPreview(this.$refs.localVideo).then(()=>{
                console.log("本地预览")
            }).catch((error) => {
                console.log("预览失败",error)
            });
        },
        //推发布流
        publish(val){
            val.configLocalAudioPublish = true;
            val.configLocalCameraPublish = true;
            val.publish().then(()=>{
                console.log("发布流成功")
            } ,(error)=>{
                console.log("发布流失败",error.message);
            });
        },

        // remote用户加入房间 onJoin
        onJoinEvent(val){
            val.on("onJoin", (publisher) => {
                console.log(publisher)
                if(publisher.userId){
                    console.log(publisher.userId)
                }
                //重置订阅状态
                //默认订阅远端音频和视频大流，但需要调用subscribe才能生效
                //这里取消默认订阅，根据需求进行订阅
                val.configRemoteAudio(publisher.userId, true);
                val.configRemoteCameraTrack(publisher.userId, true, true);
                // showAlert(publisher.displayName + "加入房间","success");
                console.log(publisher.displayName + "加入房间");
            });
        },
        //remote流发布事件 onPublish
        onPublisher(val){
            val.on("onPublisher", (publisher) => {
                val.subscribe(publisher.userId).then((userId)=>{
                    this.$nextTick(() => {
                        val.setDisplayRemoteVideo(userId,this.$refs.remoteVideo,1)
                    });
                },(error)=>{
                    console.log(error.message);
                });
            });
        },
        //remote流结束发布事件 onUnPublisher
        onUnPublisher(val){
            val.on("onUnPublisher", (publisher) => {
                console.log("onUnPublisher",publisher);
            });
        },
        // 被服务器踢出或者频道关闭时回调 onBye
        onBye(val){
            val.on("onBye",(message) =>{
                //1:被服务器踢出
                //2:频道关闭
                //3:同一个ID在其他端登录,被服务器踢出
                var msg;
                switch (message.code) {
                    case 1:
                        msg = "被服务器踢出";
                        break;
                    case 2:
                        msg = "频道关闭";
                        break;
                    case 3:
                        msg = "同一个ID在其他端登录,被服务器踢出";
                        break;
                    default:
                        msg = "onBye";
                }
                this.$notify.success({
                    title: '视频挂断',
                    message: msg
                })
                this.leaveVideo(false)
            });
        },
        leaveVideo(val){
            this.aliWebrtc.stopPreview();
            this.aliWebrtc.leaveChannel();
            this.aliWebrtc.dispose();
            this.videoDialogVisible = false
            if (val){
                deleteChannel({channelId:this.channelId}).then(res=>{

                })
            }
        },
        /**
         * 检测到用户离开频道
         * 更新用户列表
         * 移除用户视图
         */
        onLeave(val){
            val.on("onLeave", (publisher) => {
                console.log(publisher);
                this.leaveVideo(true)
            })
        },
        launchFireVideo(){
            //发起实时视频功能
            //展示弹窗区信息
            let _this = this
            launchFireVideo({fireUserId:_this.fireInfoInfo.fireUserId}).then(res=>{
                _this.channelId = res.data.channel
                this.aliWebrtc = new AliRtcEngine();
                this.isSupport(this.aliWebrtc,true)
                this.videoDialogVisible = true
                _this.$nextTick(() => {
                    _this.startPreview(_this.aliWebrtc)
                    _this.aliWebrtc.joinChannel(res.data,_this.fireInfoInfo.userName).then(obj=>{
                        _this.publish(_this.aliWebrtc)
                        console.log("加入频道成功")
                    }).catch((error)=>{
                        console.log("加入频道失败",error)
                    })
                });
            }).catch(error=>{
                this.$notify.error({
                    title: '加入频道失败',
                    message: error.msg
                })
            })
        },

      getCommanderList() {
        getCommanderList({deleted: false}).then(res => {
          this.userList = res.data
        }).catch(error => {

        })
      },
      distribution(){
        distributionPerson(this.personForm).then(res => {
          this.addLoading = false
          this.$notify.success({
            title: '成功',
            message: "分配指战员成功"
          })
          this.show=false
          this.getInFireInfoVo(this.$route.params.ucId)
        }).catch(res => {
          this.addLoading = false
          this.$notify.error({
            title: '失败',
            message: res.msg
          })
        })
      }


    }

}
</script>

<style>
.map-view{
  width: 100%;
  height: 400px;
}
</style>
